<!DOCTYPE html>
<html lang="en">

<head>
  <title>moncler demo</title>
  <meta charset="utf-8" />
  <meta name="viewport" content="width=device-width, user-scalable=no, minimum-scale=1.0, maximum-scale=1.0" />
</head>

<body>
  <script type="text/javascript" src="https://res.wx.qq.com/open/js/jweixin-1.3.2.js"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/tween.js/20.0.0/tween.umd.js"></script>
  <script src="//g.alicdn.com/mtb/lib-video-player/1.1.15/bundle/bundle.js"></script>
  
  <!-- 首页图片 -->
  <div id="homeImg" style="width:100vw;height:100vh;position: fixed; left: 0px; z-index: 9999">
    <img src="../res/poster.png"  style="width:100%;height:100%"/>
  </div>

  <!-- threejs -->
  <div id="container" style="position: fixed; left: 0px; z-index: 1"></div>
  
  <!-- 视频 -->
  <video class="lib-video vjs-hidden" style="position: fixed; left: 0px; z-index: 0" id="J_Video_Player" poster=""
    muted="false" src="" width="100%">
    <source src="../res/sintel.mp4" type="video/mp4">
    </source>
  </video>

  <!-- <button id="btn1" style="position: fixed; left: 0px; z-index: 100; display: block">播放视频</button> -->
  <script type="importmap">
    {
        "imports": {
          "three": "../build/three.module.js",
          "three/addons/": "./jsm/"
        }
      }
    </script>

  <script type="module">
    import * as THREE from 'three'

    import Stats from 'three/addons/libs/stats.module.js'

    import { GUI } from 'three/addons/libs/lil-gui.module.min.js'
    import { OrbitControls } from 'three/addons/controls/OrbitControls.js'
    import { Water } from 'three/addons/objects/Water.js'
    import { Sky } from 'three/addons/objects/Sky.js'
    import { GLTFLoader } from 'three/addons/loaders/GLTFLoader.js'
    import { RGBELoader } from 'three/addons/loaders/RGBELoader.js'

    let container, stats
    let camera, scene, renderer
    let controls, water, sun, mesh

    let video, videoTexture

    var BASE_URL = '../'

    let VideoPlayer = null;

    let myPlayer = null;
    let model = null;
    let floors = [{ x: 0, movez: -10 }, { x: 0, movez: -10 }, { movez: 0 }, {}, {}, {}, {}, {}, {}]

    let enableTouch = false;

    let loadFinish = false;

    init()
    animate()

    let homeImg = document.getElementById("homeImg")

    homeImg.onclick = ()=>{
      if(!loadFinish) return;
      homeImg.style.display = 'none'
      myPlayer.play();
      panoramaAnimate()
      touchEvent();
    };

    // 静音
    const closeVolume = (dom) => {
      dom.volume = 0
      dom.muted = true
    }
    // 开启音量
    const openVolume = (dom) => {
      dom.volume = 1
      dom.muted = false
    }

    function init() {
      container = document.getElementById('container')
      renderer = new THREE.WebGLRenderer()
      renderer.setPixelRatio(window.devicePixelRatio)
      renderer.setSize(window.innerWidth, window.innerHeight)
      renderer.toneMapping = THREE.ACESFilmicToneMapping
      renderer.toneMappingExposure = 0.6
      container.appendChild(renderer.domElement)
      scene = new THREE.Scene()
      window.scene = scene


      new RGBELoader().load(BASE_URL + 'res/royal_esplanade_1k.hdr', function(texture) {
        texture.mapping = THREE.EquirectangularReflectionMapping

        scene.background = texture
        scene.environment = texture

        render()

        // model

        const loader = new GLTFLoader()

        loader.load(BASE_URL + 'res/tower-no.glb', async function(gltf) {
          // 黑色建筑
          model = gltf.scene

          model.position.x -= 40
          model.rotation.y += Math.PI

          //model.rotation.x -= Math.PI/10.0;

          // wait until the model can be added to the scene without blocking due to shader compilation

          await renderer.compileAsync(model, camera, scene)

          scene.add(model)

          const texture1 = new THREE.TextureLoader().load(BASE_URL + 'res/BG_Tower_1_Diffuse_1KJ.png')
          texture1.colorSpace = THREE.SRGBColorSpace

          const texture2 = new THREE.TextureLoader().load(BASE_URL + 'res/BG_Tower_1_Roughness_1K.png')
          texture2.colorSpace = THREE.SRGBColorSpace

          const texture3 = new THREE.TextureLoader().load(BASE_URL + 'res/BG_Tower_1_Normal_1K.png')
          texture3.colorSpace = THREE.SRGBColorSpace

          const texture4 = new THREE.TextureLoader().load(BASE_URL + 'res/BG_Tower_1_Emission_1K.png')
          texture4.colorSpace = THREE.SRGBColorSpace

          const texture1_1 = new THREE.TextureLoader().load(BASE_URL + 'res/word_BAKE_BaseColor.png')
          texture1_1.colorSpace = THREE.SRGBColorSpace

          const texture2_1 = new THREE.TextureLoader().load(BASE_URL + 'res/word_BAKE_Roughness.png')
          texture2_1.colorSpace = THREE.SRGBColorSpace

          const texture3_1 = new THREE.TextureLoader().load(BASE_URL + 'res/word_BAKE_Normal.png')
          texture3_1.colorSpace = THREE.SRGBColorSpace

          const texture4_1 = new THREE.TextureLoader().load(BASE_URL + 'res/word_BAKE_Emissive.png')
          texture4_1.colorSpace = THREE.SRGBColorSpace
          
          // 大楼模板
          var tower = model.getObjectByName('Genius_City_BG_Tower_1_DEMO')

          var tmpArray = tower.geometry.attributes.uv.array
          for (var i = 0; i < tmpArray.length / 2; i++) {
            tmpArray[i * 2 + 1] = 1.0 - tmpArray[i * 2 + 1]
          }
          tower.geometry.attributes.uv.array = tmpArray
          tower.geometry.attributes.uv.needsUpdate = true

          tower.material.map = texture1
          tower.material.metalnessMap = texture2
          tower.material.roughnessMap = texture2
          tower.material.normalMap = texture3
          tower.material.emissiveMap = texture4
          tower.material.needsUpdate = true
          
          // 克隆大楼
          function addTower(source, name, x, z, isBlack = false) {
            let initX = 8.0
            var tower_clone = model.getObjectByName(source).clone()
            tower_clone.name = name
            
            // 材质替换就可以
            tower_clone.material = tower.material.clone()
            tower_clone.material.transparent = true;
            tower_clone.material.opacity = 1;

            tower.parent.add(tower_clone)
            tower_clone.position.x -= initX + x

            if(!isBlack) {
              tower_clone.material.map = texture1_1
              tower_clone.material.metalnessMap = texture2_1
              tower_clone.material.roughnessMap = texture2_1
              tower_clone.material.normalMap = texture3_1
              tower_clone.material.emissiveMap = texture4_1
              tower_clone.material.needsUpdate = true
            }
            

            // console.log(tower_clone)

            return tower_clone
          }
           
          function addVideoFloor(){
            // 第二栋楼
            let addTowerVideo = addTower('Genius_City_BG_Tower_1_DEMO', 'Genius_City_BG_Tower_1_DEMO_0', 0, -1)
            VideoPlayer = lib.videoPlayer;
            console.log('VideoPlayer====', VideoPlayer);
            
            myPlayer = VideoPlayer('J_Video_Player', {
              // 'custom-controls': 'true' //展示底部控制栏
              'custom-controls': 'false' //隐藏底部控制栏
            });
            myPlayer.on('video:ended', () => { //监听视频结束事件
              myPlayer.play();
            });

            setTimeout(() => {
              let video = myPlayer.getVideoEl()
              closeVolume(video)
              myPlayer.play();
              
              videoTexture = new THREE.VideoTexture(video)
              videoTexture.colorSpace = THREE.SRGBColorSpace

              let material = new THREE.MeshBasicMaterial({ side: THREE.DoubleSide })
              addTowerVideo.material = material
              addTowerVideo.material.transparent = true;
              addTowerVideo.material.opacity = 1;
              addTowerVideo.material.map = videoTexture
              window.addTowerVideo = addTowerVideo
            }, 500)
          }
          
         
          // 创建第二栋楼 == 黑色
          addTower('Genius_City_BG_Tower_1_DEMO', 'Genius_City_BG_Tower_1_DEMO_0_black', 0, -1,true)

          // 创建第二栋楼==视频楼
          addVideoFloor();


          // 其余的楼
          for (let i in floors) {
              let num = Number(i)
              // 黑色楼
              addTower('Genius_City_BG_Tower_1_DEMO', 'Genius_City_BG_Tower_1_DEMO' + '_' + (num + 1)+ '_black', (num + 1) * 8, -(num + 1),true)
              
              // 黄色楼
              addTower('Genius_City_BG_Tower_1_DEMO', 'Genius_City_BG_Tower_1_DEMO' + '_' + (num + 1), (num + 1) * 8, -(num + 1))
          }

          render()
        })
      })

      camera = new THREE.PerspectiveCamera(55, window.innerWidth / window.innerHeight, 1, 20000)
      camera.position.set(0, 0, 1000)
      sun = new THREE.Vector3()

      // Water

      const waterGeometry = new THREE.PlaneGeometry(10000, 10000)

      water = new Water(waterGeometry, {
        textureWidth: 512,
        textureHeight: 512,
        waterNormals: new THREE.TextureLoader().load(BASE_URL + 'res/waternormals.jpg', function(texture) {
          texture.wrapS = texture.wrapT = THREE.RepeatWrapping
        }),
        sunDirection: new THREE.Vector3(),
        sunColor: 0xffffff,
        waterColor: 0x001e0f,
        distortionScale: 3.7,
        fog: scene.fog !== undefined,
      })

      water.rotation.x = -Math.PI / 2

      scene.add(water)

      // Skybox

      const sky = new Sky()
      sky.scale.setScalar(10000)
      scene.add(sky)

      const skyUniforms = sky.material.uniforms

      skyUniforms['turbidity'].value = 10
      skyUniforms['rayleigh'].value = 2
      skyUniforms['mieCoefficient'].value = 0.005
      skyUniforms['mieDirectionalG'].value = 0.8

      const parameters = {
        elevation: -3, //时间
        azimuth: -28,
      }

      const pmremGenerator = new THREE.PMREMGenerator(renderer)
      const sceneEnv = new THREE.Scene()

      let renderTarget

      function updateSun() {
        const phi = THREE.MathUtils.degToRad(90 - parameters.elevation)
        const theta = THREE.MathUtils.degToRad(parameters.azimuth)

        sun.setFromSphericalCoords(1, phi, theta)

        sky.material.uniforms['sunPosition'].value.copy(sun)
        water.material.uniforms['sunDirection'].value.copy(sun).normalize()

        if (renderTarget !== undefined) renderTarget.dispose()

        sceneEnv.add(sky)
        renderTarget = pmremGenerator.fromScene(sceneEnv)
        scene.add(sky)

        scene.environment = renderTarget.texture
      }

      updateSun()


      controls = new OrbitControls(camera, renderer.domElement)
      controls.enableRotate = false // 禁用旋转
      controls.maxPolarAngle = Math.PI * 0.495
      controls.target.set(0, 5, 0)
      // controls.minDistance = 40.0
      // controls.maxDistance = 200.0
      controls.minDistance = 20.0
      controls.maxDistance = 300.0
      controls.update()
      window.controls = controls
    


      stats = new Stats()
      //container.appendChild( stats.dom );

      // GUI

      // const gui = new GUI();

      // const folderSky = gui.addFolder( 'Sky' );
      // folderSky.add( parameters, 'elevation', 0, 90, 0.1 ).onChange( updateSun );
      // folderSky.add( parameters, 'azimuth', - 180, 180, 0.1 ).onChange( updateSun );
      // folderSky.open();

      // const waterUniforms = water.material.uniforms;

      // const folderWater = gui.addFolder( 'Water' );
      // folderWater.add( waterUniforms.distortionScale, 'value', 0, 8, 0.1 ).name( 'distortionScale' );
      // folderWater.add( waterUniforms.size, 'value', 0.1, 10, 0.1 ).name( 'size' );
      // folderWater.open();

      //

      window.addEventListener('resize', onWindowResize)


      setTimeout(()=>{
        loadFinish = true;
      },3000)
    }

    function onWindowResize() {
      camera.aspect = window.innerWidth / window.innerHeight
      camera.updateProjectionMatrix()

      renderer.setSize(window.innerWidth, window.innerHeight)
    }

    function animate() {
      requestAnimationFrame(animate)
      render()
      stats.update()
      TWEEN.update()
    }

    function render() {
      const time = performance.now() * 0.001

      // mesh.position.y = Math.sin( time ) * 20 + 5;
      // mesh.rotation.x = time * 0.5;
      // mesh.rotation.z = time * 0.51;

      water.material.uniforms['time'].value += 1.0 / 60.0

      renderer.render(scene, camera)
    }

    // 全景动画
    function panoramaAnimate(){
      new TWEEN.Tween(model.position).
      to({ x:0 }, 1500).start()
      .easing(TWEEN.Easing.Sinusoidal.InOut)


      new TWEEN.Tween(controls.object.position).
      to({z: 40 }, 1500).onComplete(()=>{
        enableTouch = true;
      }).start()
      .easing(TWEEN.Easing.Sinusoidal.InOut)
      

      let towers = scene.children[2].children;
      // 让除了第一个的楼贴图边成黑色
      for(let i=0;i<10;i++){
        // console.log(towers)
        for(let item of towers) {
          if(item.name == `Genius_City_BG_Tower_1_DEMO_${i}`){
            //  console.log('item',item);
             new TWEEN.Tween(item.material).
              to({ opacity:0 }, 1500).start()
              .easing(TWEEN.Easing.Sinusoidal.InOut)
          }
        }
      }
      
    }
    
    // 触摸事件
    function touchEvent(){
      let startX = 0
      let endX = 0
      
      container.addEventListener('touchstart', function(event) {
        if(!enableTouch) return;
        event.preventDefault()
        startX = event.touches[0].pageX
        console.log('touchstart_____', startX)
      })

      container.addEventListener('touchend', function(event) {
        if(!enableTouch) return;
        enableTouch = false;
        event.preventDefault()

        let towers = [];
        for(let i=0;i<10;i++){
        // console.log(towers)
          for(let item of scene.children[2].children) {
            if(item.name == `Genius_City_BG_Tower_1_DEMO_${i}`){
              towers.push(item)
            }
          }
        }

        endX = event.changedTouches[0].pageX
        console.log('touchend_______', endX)
        let detalX = endX - startX;
        if (detalX > 0) {
          console.log('左移', model.position.x)
          if(model.position.x >= 0) return enableTouch = true; 
          
          // 根据移动的距离判断哪栋楼该贴黄色贴图
          // console.log('towers',towers);


          console.log(Math.abs(model.position.x) / 8)

          let currentIndex = Math.abs(model.position.x) / 8

          // console.log('towers++++',towers[currentIndex-1].material);
         
          if(currentIndex-2 >= 0) {
            const tween1 = new TWEEN.Tween(towers[currentIndex-2].material).
           to({ opacity: 1 }, 800).start()
           .easing(TWEEN.Easing.Sinusoidal.InOut)//进入和结束都设置缓动
          }
          
           
          if(currentIndex-1 >=0) {
            const tween2 = new TWEEN.Tween(towers[currentIndex-1].material).
           to({ opacity: 0 }, 800).start()
          .easing(TWEEN.Easing.Sinusoidal.InOut)//进入和结束都设置缓动
          }

          const tween3 = new TWEEN.Tween(model.position)
          .to({ x: model.position.x + 8 }, 800).onComplete(()=>{
            enableTouch = true;
          }).start()
          .easing(TWEEN.Easing.Sinusoidal.InOut)//进入和结束都设置缓动

        } else {
          console.log('右移', model.position.x)
          if(model.position.x < -72) return enableTouch = true;
          
          // 根据移动的距离判断哪栋楼该贴黄色贴图
          // console.log('towers',towers);

          console.log(Math.abs(model.position.x) / 8)

          let currentIndex = Math.abs(model.position.x) / 8

          const tween1 = new TWEEN.Tween(towers[currentIndex].material).
          to({ opacity: 1 }, 800).start()
          .easing(TWEEN.Easing.Sinusoidal.InOut)//进入和结束都设置缓动
           
          if(currentIndex - 1 >=0) {
            const tween2 = new TWEEN.Tween(towers[currentIndex - 1].material).
           to({ opacity: 0 }, 800).start()
          .easing(TWEEN.Easing.Sinusoidal.InOut)//进入和结束都设置缓动
          }
 

          

          const tween = new TWEEN.Tween(model.position).
          to({ x: model.position.x - 8 }, 800).onComplete(()=>{
            enableTouch = true
          }).start()
          .easing(TWEEN.Easing.Sinusoidal.InOut)//进入和结束都设置缓动
        }
      })
    };

    // 根据移动距离判断当前应该点亮的
  </script>
</body>

</html>